// ETF.cc -- the main program for the External Target Facility
// Created: Jan. 28, 2019, by Asia SUN, asia.rabbit@163.com
// Last modified: Nov. 13, 2023, by Asia SUN

#include "EG4DetConstruct.h"
#include "EG4ActionInit.h"
#include "G4RunManager.hh"
#include "G4UImanager.hh"
#include "FTFP_BERT.hh"
#include "G4StepLimiterPhysics.hh"
#include "G4VisExecutive.hh"
#include "G4UIExecutive.hh"
#include "EG4ROOT.h"
#include "EG4ParaManager.h"

int main(int argc, char **argv){
  EG4ParaManager::Instance()->ReadParameters();
  // Detect interactive mode (if no arguments) and define UI session
  G4UIExecutive *ui = nullptr;
  if(1 == argc) ui = new G4UIExecutive(argc, argv, "qt"); // no arguments
  auto rm = new G4RunManager();

  // mandatory user initialization classes
  rm->SetUserInitialization(new EG4DetConstruct());
  auto pl = new FTFP_BERT();
  pl->RegisterPhysics(new G4StepLimiterPhysics());
  rm->SetUserInitialization(pl);
  EG4ROOT *root = new EG4ROOT(); // an interface to ROOT
  EG4ActionInit *actionInit = new EG4ActionInit(root);
  // actionInit->SetUsingGun();
  rm->SetUserInitialization(actionInit);
  rm->Initialize();

  // visualization manager construction
  auto vm = new G4VisExecutive();
  vm->Initialize();

  G4UImanager *uim = G4UImanager::GetUIpointer();
  if(!ui){ // execute an argument macro file if exist
    G4String command = "/control/execute ";
    G4String fileName = argv[1];
    uim->ApplyCommand(command + fileName);
  } else{ // directly show graphical images
    if(ui->IsGUI()){
      uim->ApplyCommand("/control/execute ../g4/config/gui.mac");
      uim->ApplyCommand("/control/execute ../g4/config/init_vis.mac");
    } // end if
    ui->SessionStart();
    delete ui;
  } // end else

  root->Finish();
  delete vm;
  delete rm;

  return 0;
} // end of main function
